<template>
  <div class="xd-LearningHome-VideoCourse p_10">
    <div style="height: 35px">
      <a
        style="cursor: pointer; color: #cb2c21; font-weight: bold"
        @click="goView('/LearningHome', {})"
        >理论学习</a
      >
      ＞
      <a
        style="cursor: pointer; color: #cb2c21; font-weight: bold"
        @click="
          goView('/LearningHome/Learning/CourseIntroduction', {
            tid: curriculumId,
          })
        "
        >{{ curriculumTitle }}</a
      >
    </div>
    <el-card shadow="hover">
      <!--图片底色为#f4f4f4 -->
      <el-row
        :style="
          'background-color:' +
          (currentCourseware.coursewareType === 1 ? '#f4f4f4' : '#14191d')
        "
      >
        <el-col :span="18">
          <!-- 1、图片 -->
          <template v-if="currentCourseware.coursewareType === 1">
            <div
              class="video-panel"
              v-for="enclosure in currentCourseware.coursewareEnclosureList"
              :key="enclosure.id"
            >
              <el-image
                :src="enclosure.filePath"
                :preview-src-list="imgList"
              ></el-image>
            </div>
          </template>
          <!-- 2、视频 mp4 -->
          <template v-else-if="currentCourseware.coursewareType === 2">
            <div class="video-panel mp4" v-if="isLoaded">
              <CkplayerVideo
                ref="flvVideoPlayer"
                :videoUrl="
                  currentCourseware.coursewareEnclosureList[0].filePath
                "
                :stime="videoStartTime"
                :timeScheduleAdjust="timeScheduleAdjust"
                @playbackRateHandler="playbackRateHandler"
              ></CkplayerVideo>
            </div>
            <div class="video-panel mp4" v-else style="height: 350px">
              视频努力加载中...
            </div>
          </template>
          <!-- 3、音频 MP3、Wav-->
          <template v-else-if="currentCourseware.coursewareType === 3">
            <div
              class="video-panel"
              style="text-align: center; padding-top: 30px"
            >
              <audio
                style="width: 100%"
                :src="currentCourseware.coursewareEnclosureList[0].filePath"
                controls="controls"
              >
                您的浏览器不支持 audio 标签。
              </audio>
            </div>
          </template>
          <!-- 4、文档 只支持 pdf -->
          <template v-else-if="currentCourseware.coursewareType === 4">
            <div class="video-panel">
              <div class="pdf-mask" v-if="isOpenPdfViewBig"></div>
              <img
                src="@/assets/imgs/zdh.png"
                title="最大化"
                style="
                  float: right;
                  display: block;
                  cursor: pointer;
                  width: 36px;
                  height: 36px;
                  margin-bottom: 5px;
                "
                @click="doOpenPdfViewBig()"
              />
              <div
                style="height: 600px;"
                :class="[isOpenPdfViewBig ? 'open-pdf-view-big' : '']"
              >
                <img
                  src="@/assets/imgs/close.png"
                  title="关闭"
                  style="cursor: pointer"
                  class="pdf-view-big-close"
                  v-if="isOpenPdfViewBig"
                  @click="isOpenPdfViewBig = false"
                />
                <embed
                  :src="currentCourseware.coursewareEnclosureList[0].filePath"
                  style="height: 100%; width: 99%"
                />   
                <!-- <PdfView :pdfUrl="currentCourseware.coursewareEnclosureList[0].filePath"></PdfView> -->
              </div>
            </div>
          </template>
          <div style="font-size: 9px; color: red; padding: 0px 5px 5px 5px">
            学习进度(秒){{ time }}/{{
              currentCourseware.validTimeLong * 60
            }}
            ({{
              Math.floor((time / (currentCourseware.validTimeLong * 60)) * 100)
            }}%)
          </div>
        </el-col>
        <el-col :span="6" class="course-panel">
          <p
            :class="
              currentCourseware.coursewareType === 1 ? 'img-title' : 'title'
            "
            v-text="detail.chapterTitle"
          ></p>
          <ul>
            <li
              v-for="(item, index) in detail.coursewareList"
              :key="item.coursewareId"
              :class="[activeIndex === index ? 'active' : '']"
              @click="itemClick(index)"
            >
              <i
                :class="[
                  activeIndex === index
                    ? 'el-icon-video-play'
                    : 'el-icon-video-pause',
                ]"
              ></i>
              <span v-text="item.coursewareName"></span>
            </li>
          </ul>
        </el-col>
      </el-row>

      <div class="m_t_15 comments-panel">
        <el-tabs v-model="activeName" class="el-tabs-first-indent">
          <el-tab-pane label="评论" name="tabPl">
            <el-input
              type="textarea"
              :rows="5"
              placeholder="请输入评论内容"
              v-model="content"
              maxlength="1000"
               show-word-limit
            ></el-input>
            <el-button
              type="primary"
              style="display: flex;width: 5.2vw;"
              @click="publishComments"
              :loading="submitLoading" 
              >发表</el-button
            >
          </el-tab-pane>
          <el-tab-pane label="学习笔记" name="tabXxxd">
            <el-input
              type="textarea"
              :rows="5"
              placeholder="请输入学习笔记"
              maxlength="1000"
              v-model="studyNotesContent"
              show-word-limit
            ></el-input>
            <div style="text-align:right;">
                 <el-button
                type="primary"
                 style="width: 5.2vw;"
                @click="saveStudyNotes"
                :loading="submitLoading"
                >保存</el-button
              >
              <el-button @click="clearStudyNotes"  style="width: 5.2vw;"
                >清空</el-button > 
            </div>
            <ul class="xxbj_item_flex_ul">
              <li
                v-for="(item, index) in studyNotesList"
                :key="index"
                @click="studyNotesClick(item)"
              >
                <span class="title">· {{ item.note }}</span>
                <span class="time">{{
                  spliceDateString(item.createTime)
                }}</span> &nbsp;&nbsp;
                <i class="el-icon-delete" @click="studyNotesDel(item)"></i>
              </li>
            </ul>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>

    <InteractVerify
      ref="verify"
      @success="onVerifySuccess"
      @fail="onVerifyFail"
    ></InteractVerify>
      <pdf-max-view ref="pdfMaxView"></pdf-max-view>
    <!-- 切换课件显示加载中 避免重复点击定时器bug -->
    <div :class="'open-loading'" v-if="isLoading">
      <div class="box">切换中...</div>
    </div>
  </div>
</template>
<script>
const InteractVerify = () => import("../../../components/InteractVerify");
const CkplayerVideo = () => import("../../../components/CkplayerVideo");
const PdfMaxView = () => import('./PdfMaxView')

//  页面离开要clear
var timeFlg = null;
export default {
  name: "VideoCourse",
  components: {
    InteractVerify,
    CkplayerVideo, 
    PdfMaxView
  },
  data() {
    return {
      activeName: "tabPl",
      isLoading: false,
      curriculumId: "", // 课程id
      curriculumTitle: "", // 课程名称
      detail: {},
      activeIndex: 0,
      activeCoursewareId: 0,
      currentCourseware: {}, // 当前课件
      content: "",
      submitLoading: false,
      selectStudyNotesId: "", //选择的学习笔记id
      studyNotesContent: "", //学习笔记
      time: 0,
      isStop: false,
      isCompleted: 0,
      isLoaded: false, // 是否加载完成

      vTime: 0, // 验证码开始时间 120s 弹一次 重置0
      sTime: 0, // 提交间隔时间 60s 提交一次
      videoStartTime: 0, // 视频开始时间 默认和time ,time 为100 videoStartTime 为0
      isOpenPdfViewBig: false, // 是否最大化pdf预览
      studyNotesList: [],
      intervalTime:1000,//进度间隔时长（毫秒）
      recordId:'',//学习记录id
    };
  },
  computed: {
    imgList() {
      return this.currentCourseware.coursewareEnclosureList.map((item) => {
        return item.filePath;
      });
    },
    timeScheduleAdjust() {
      return this.isCompleted == 1 ? 1 : 5;
    },
  },
  created() {
    this.detail = utils.getItem("startLearning");
    this.curriculumId = this.$route.query.tid;
    this.activeIndex = this.$route.query.coursewareIndex;
    this.currentCourseware = this.detail.coursewareList[this.activeIndex];
    this.activeCoursewareId = this.$route.query.coursewareId;
    this.curriculumId = this.$route.query.curriculumId; // 课程id
    this.curriculumTitle = this.$route.query.curriculumTitle;
    this.isCompleted = this.$route.query.isCompleted;
    // this.timeScheduleAdjust = this.isCompleted == 1 ? 1 : 5;
  },
  mounted() {
    // eslint-disable-next-line
    this.begin();
    this.queryStudyNotes();
  },
  beforeDestroy() {
    // console.log('离开');
    this.isStop = true;
    if (this.$refs.flvVideoPlayer) {
      this.$refs.flvVideoPlayer.clear();
    }
    this.clearTimer();
  },
  methods: {
    doOpenPdfViewBig(){
      //this.isOpenPdfViewBig = true
      this.$refs.pdfMaxView.open(this.curriculumTitle,this.recordId,this.currentCourseware.coursewareEnclosureList[0].filePath);
    },
    begin() {
      if (this.isCompleted == 1) {
        this.isLoaded = true;
        this.time = this.currentCourseware.validTimeLong * 60;
        this.videoStartTime = 0;
        // console.log('begin:' + this.time);
        this.isLoading = false;
        this.loadRecordId();
      } else {
        this.load1();
        this.isStop = false;
      }
    },
    loadRecordId(){//获取学习记录
      utils.post(
            "/curriculum/getChapterStudyRecord",
            {
              curriculumId: this.curriculumId,
              chapterId: this.detail.chapterId,
              coursewareId: this.activeCoursewareId,
            },
            (res) => {
              if (res.code===1) {
                this.recordId = res.data.recordId;
              } 
            }
          );
    },
    load1() {
      var that = this;
      this.submitStudy(function () {
        that.startStudy(); // 开 始、继续学习
      });
    },
    goView(url, query) {
      query = query || {};
      if (url) {
        this.$router.push({ path: url, query: query });
      } else {
        this.$notify.info("暂未发布，敬请期待！");
      }
    },
    itemClick(index) {
      if (this.activeIndex === index) {
        return;
      }

      this.activeIndex = index;
      this.currentCourseware = this.detail.coursewareList[index];
      this.activeCoursewareId = this.currentCourseware.coursewareId;
      this.isCompleted = this.currentCourseware.isCompleted;
      this.videoStartTime = 0;
      this.time = 0;
      this.isStop = true;
      if (this.$refs.flvVideoPlayer) {
        this.$refs.flvVideoPlayer.clear();
      }
      this.clearTimer();
      this.isLoading = true; //显示加载中 避免重复点击定时器bug
      this.begin();
      // console.log(this.currentCourseware);
      // this.$router.push({
      //   path: '/LearningHome/Learning/VideoCourse?ddd',
      //   query: {
      //     tid: this.tid,
      //     coursewareIndex: index,
      //     coursewareId: this.currentCourseware.coursewareId,
      //     curriculumId: this.curriculumId, // 课程id
      //     curriculumTitle: this.currentCourseware.curriculumTitle, // 课程名称
      //     isCompleted: this.currentCourseware.isCompleted // 课件完成状态
      //   }
      // })
      // window.location.reload()
    },
    publishComments() {
      this.submitLoading = true;
      utils.post(
        "/curriculum/chapterComment",
        {
          curriculumId: this.curriculumId,
          chapterId: this.detail.chapterId,
          questionContent: this.content,
        },
        (res) => {
          if (res.success) {
            this.content = "";
            this.$message({
              message: "评论成功",
              type: "success",
            });
          }
          this.submitLoading = false;
        }
      );
    },
    saveStudyNotes() {
      //学习笔记
      this.submitLoading = true;
      var param = {
        curriculumId: this.curriculumId,
        chapterId: this.detail.chapterId,
        note: this.studyNotesContent,
      };
      if (this.selectStudyNotesId) {
        param.id = this.selectStudyNotesId;
      }
      utils.post("/curriculum/chapterStudyNotes/add", param, (res) => {
        if (res.success) {
          this.studyNotesContent = "";
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.queryStudyNotes();
        }
        this.submitLoading = false;
      });
    },
    clearStudyNotes() {
      this.selectStudyNotesId = "";
      this.studyNotesContent = "";
    },
    queryStudyNotes() {
      //学习笔记列表
      var that = this;
      utils.post(
        "/curriculum/chapterStudyNotes/list",
        {
          curriculumId: this.curriculumId,
          chapterId: this.detail.chapterId,
        },
        (res) => {
          if (res.success) {
            that.studyNotesList = res.data;
          }
        }
      );
    },
    studyNotesClick(obj) {
      this.selectStudyNotesId = obj.id;
      this.studyNotesContent = obj.note;
    },
    studyNotesDel(obj) {
      //学习笔记列表
      var that = this;
      this.$confirm("确认删除该学习笔记？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        utils.post(
          "/curriculum/chapterStudyNotes/delete",
          {
            id: obj.id,
          },
          (res) => {
            if (res.success) {
              that.$message({
                message: "删除成功",
                type: "success",
              });
              that.queryStudyNotes();
            }
          }
        );
      });
    },
    submitStudy(callback) {
      utils.post(
        "/curriculum/startChapterStudy",
        {
          curriculumId: this.curriculumId,
          chapterId: this.detail.chapterId,
          coursewareId: this.activeCoursewareId,
          isCompleted: this.isCompleted,
          completeSecond: this.time,
        },
        (res) => {
          this.isLoaded = true;
          if (res.code === 402) {
            // 已完成学习
            this.isCompleted = 1;
            this.time = this.currentCourseware.validTimeLong * 60;
            this.videoStartTime = 0;
          }
          if (res.code === 1) {
            this.time = res.data.time || 0;
            this.videoStartTime = this.time;
            this.vTime = this.time;
            if (res.data.points && res.data.points > 0) {
              //只要返回积分>0 就给提示
              this.$notify({
                title: "提示",
                message: "恭喜您获得 " + res.data.points + " 积分",
                type: "success",
              });
            }
            this.recordId = res.data.recordId;//学习记录id
          }
          if (callback) {
            callback();
          }
        }
      );
      if (this.isCompleted === 1) {
        this.clearTimer();
      }
    },
    startStudy() {
      var that = this;
      // console.log('startTime');
      timeFlg = setInterval(() => {   
        // console.log('time:' + this.time + ' isStop:' + this.isStop);
        if (this.isStop) {
          this.clearTimer();
          return;
        }
        var totalS = this.currentCourseware.validTimeLong * 60; // 总秒数
        this.time++;
        this.vTime++; // 验证码++
        this.sTime++; // 提交时间++
        // 课程中途播放一半弹验证码
        if (this.vTime === this.currentCourseware.validTimeLong * 30) {
          // 剩余时长
          var cs = totalS - that.time;
          if (cs > 10) {
            //  剩余时长 > 10s 才弹
            this.vTime = 0;
            this.clearTimer();
            console.log("call get verify");
            this.$refs["verify"].getVerify();
          }
        }

        if (this.sTime === 60) {
          // 60s提交一次请求
          this.sTime = 0;
          this.submitStudy();
        }

        if (location.href.indexOf("LearningHome/Learning/VideoCourse") === -1) {
          return;
        }
        var pro = Math.floor((this.time / totalS) * 100);
        if (pro >= 100) {
          this.clearTimer();
          this.$notify({
            title: "提示",
            message: "恭喜您完成本章节学习。",
            type: "success",
          });
          this.isCompleted = 1;
          this.detail.coursewareList[this.activeIndex].isCompleted = 1;
          // 学习完成以后重新赋值isCompleted，并重新加载视频控件
          this.submitStudy(() => {
            const newQuery = JSON.parse(JSON.stringify(this.$route.query));
            Object.assign(newQuery, { isCompleted: this.isCompleted });
            this.$router.push({ query: newQuery });
          });
          this.isStop = true;
          // if (this.$refs.flvVideoPlayer) {
          //     this.$refs.flvVideoPlayer.pause();
          //     this.$refs.flvVideoPlayer.quitFullScreen();
          // }
        }
      }, that.intervalTime);
      this.isLoading = false;
    },
    clearTimer() {
      if (timeFlg) {
        clearInterval(timeFlg);
        timeFlg = 0;
        // console.log('endTime-clear');
      }
    },
    onVerifySuccess() {
      if (this.isStop) {
        this.isStop = false;
        if (this.$refs.flvVideoPlayer) {
          this.$refs.flvVideoPlayer.play();
        }
      }
      this.startStudy();
    },
    onVerifyFail() {
      // 暂停播放、退出全屏
      this.isStop = true;
      if (this.$refs.flvVideoPlayer) {
        this.$refs.flvVideoPlayer.pause();
        try {
          this.$refs.flvVideoPlayer.quitFullScreen();
        } catch (error) {
          console.log(error);
        }
      }
      this.clearTimer();
    },
    playbackRateHandler(num){//改变倍速
         this.clearTimer(); 
         this.intervalTime = Math.floor(1000/num)
         this.startStudy();
    },
  },
};
</script>
<style lang="less">
.xd-LearningHome-VideoCourse {
  .el-card__body {
    padding: 0px;
  }

  .video-panel {
    padding: 0px 0.8vw 0.8vw 0.8vw;
    overflow: hidden;
    color: #ffffff;
    video {
      height: 22.5vw;
      width: 100%;
    }
  }

  .course-panel {
    .title {
      background: #1f2428;
      font-size: 0.8vw;
      color: #999999;
      height: 2.1vw;
      display: flex;
      align-items: center;
      padding-left: 0.8vw;
    }

    .active {
      color: #087d6a;
    }

    ul {
      list-style: none;
      padding: 0;
      padding-left: 0.8vw;
      li {
        color: #999999;
        font-size: 0.7vw;
        padding-bottom: 0.5vw;
        display: flex;
        align-items: center;
        cursor: pointer;
        i {
          font-size: 1vw;
        }
        span {
          margin-left: 0.5vw;
        }
      }
    }
  }

  .comments-panel {
    padding: 20px;

    .el-textarea {
      border-radius: 0.5vw;
      margin-top: 1vw;
      background-color: #f1f1f1;
      .el-textarea__inner {
        background: transparent;
        border-color: #f1f1f1;
        border-radius: 0.5vw;
      }
    }

    .el-button--primary { 
      margin-left: auto; 
      margin-top: 1vw;
      justify-content: center;
      background-color: #cb2c21;
      border-color: #cb2c21;
    }
  }
}

.courseware-image {
  width: 100%;
  height: 100%;
}

.xd-LearningHome-VideoCourse .open-loading {
  background-color: black;
  opacity: 0.7;
  border: 1px solid rgb(114, 22, 22);
  width: 100%;
  height: 100% !important;
  position: fixed;
  z-index: 999;
  right: 0%;
  top: 0%;
  padding: 10px;
  background-clip: padding-box;
  color: #fff;
  text-align: center;
  border: 1px solid rgba(0, 0, 0, 0);
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
  .box {
    font-size: 40px;
    width: 200px;
    height: 100px;
    line-height: 100px;
    text-align: center; /*让文字水平居中*/
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -100px;
  }
}

//最大化pdf css
.xd-LearningHome-VideoCourse .open-pdf-view-big {
  background: #000;
  border: 1px solid #ddd;
  width: 80%;
  height: 90% !important;
  position: fixed;
  z-index: 999;
  right: 10%;
  top: 3%;
  padding: 10px;
  background-clip: padding-box;
  background-color: #000;
  border: 1px solid rgba(0, 0, 0, 0);
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}
.xd-LearningHome-VideoCourse .open-pdf-view-big .pdf-view-big-close {
  top: -1px;
  float: right;
  position: inherit;
  right: -1px;
}

.xd-LearningHome-VideoCourse .pdf-mask {
  z-index: 900;
  position: fixed !important;
  position: absolute;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  background: #000;
  filter: alpha(opacity=45);
  opacity: 0.65;
  -moz-opacity: 0.65;
  -khtml-opacity: 0.65;
}

.xd-LearningHome-VideoCourse .course-panel .img-title {
  background: #006756;
  font-size: 0.8vw;
  color: #fff;
  height: 2.1vw;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  padding-left: 0.8vw;
}

ul.xxbj_item_flex_ul {
  padding: 0px 25px 0px 5px;
  margin-top: 18px;
  li {
    cursor: pointer;
    font-size: 16px;
    list-style: none;
    color: #333333;
    display: flex;
    align-items: center;
    line-height: 30px;
    overflow: hidden;
    text-align: left;
    .title {
      width: 0px;
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .time {
      color: #999999;
      margin-left: auto;
      margin-right: 0px;
    }
  }
}
</style>